package io.adrainty.bolee.security.satoken.handler;

import io.adrainty.bolee.framework.commons.basic.ResultDTO;
import io.adrainty.bolee.framework.commons.user.UserEntity;
import io.adrainty.bolee.framework.commons.utils.ResultDTOUtil;
import io.adrainty.bolee.security.models.constants.OAuth2Constants;
import io.adrainty.bolee.security.models.entity.CompanyEntity;
import io.adrainty.bolee.security.models.valobj.GrantTypeEnum;
import io.adrainty.bolee.security.models.valobj.LoginTypeEnum;
import io.adrainty.bolee.security.models.valobj.UserTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * <p>SsoPasswordGrantTypeHandler</p>
 *
 * @author AdRainty
 * @version V1.0.0
 * @description PasswordGrantTypeHandler
 * @since 2025/8/6 11:23:20
 */

@Slf4j
@Component
public class PasswordGrantTypeHandler extends BaseGrantTypeHandler {

    @Override
    protected UserEntity doGrantHandler(UserTypeEnum userType, Map<String, String> parameters, CompanyEntity companyEntity) {
        String username = parameters.get(OAuth2Constants.USER_NAME_KEY);

        // 获取用户信息
        ResultDTO<UserEntity> resultDTO = switch (userType) {
            case USER -> userFeign.usernameLogin(username, companyEntity.getCompanyNo());
            case CUSTOMER -> customerFeign.usernameLogin(username, companyEntity.getCompanyNo());
        };

        UserEntity userEntity = ResultDTOUtil.assertResultDataNotNull(resultDTO);
        log.info("根据用户名查找用户结果: {}", userEntity.getId());
        return userEntity;
    }

    @Override
    public String getHandlerGrantType() {
        return GrantTypeEnum.PASSWORD.getCode();
    }

    @Override
    public String getActualGrantType() {
        return LoginTypeEnum.USERNAME.getCode();
    }
}
